import logging

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', help='print debug logging output to console')
parser.add_argument('-f', '--feed', help='Atom feed file to test parsing')

args = parser.parse_args()

if args.debug:
    logging.basicConfig(level=logging.DEBUG)


import pytz
from datetime import datetime
tz = pytz.utc

from atomparser import atomprop

if args.feed:
    with open(args.feed, 'r') as xml:
        atom = atomprop.AtomFeed(xml)
else:
    atom = atomprop.AtomFeed(author={'name': 'Test Tester'})
    e = atomprop.AtomEntry(content='Something I wrote.')
    e.title = 'post 1'
    atom.entries.append(e)

for propname in ['title', 'subtitle', 'id', 'author', 'updated', 'next', 'prev']:
    try:
        prop = getattr(atom, propname)
        if isinstance(prop, atomprop.AtomAuthor):
            print('\t{}:\t{}'.format(propname.capitalize(), prop.name.get_value()))
        else:
            print('\t{}:\t{}'.format(propname.capitalize(), prop.get_value()))
    except AttributeError as e:
        logging.debug('\t{}:\tnot set ({})'.format(propname.capitalize(), e))
        pass
    except KeyError as e:
        logging.debug('\t{}:\tnot set ({})'.format(propname.capitalize(), e))
        pass

print('\tEntries: {}'.format(len(atom.entries)))
for i in range(atom.entries.length):
    print('\tEntry {}'.format(i))
    for propname in ['title', 'id', 'author', 'published', 'updated', 'categories', 'summary', 'content']:
        try:
            prop = getattr(atom.entries[i], propname)
            if isinstance(prop, atomprop.DateConstruct):
                print('\t\t{}:\t{}'.format(propname.capitalize(), tz.normalize(prop.get_value())))
            elif isinstance(prop, atomprop.AtomAuthor):
                print('\t\t{}:\t{}'.format(propname.capitalize(), prop.name.get_value()))
            elif isinstance(prop, atomprop.AtomCategories) and prop.length > 0:
                print('\t\t{}:\t{}'.format(propname.capitalize(), ', '.join(val.get('term') for val in prop)))
            else:
                try:
                    print('\t\t{}:\t{}'.format(propname.capitalize(), prop.get_value()))
                except AttributeError as e:
                    pass
        except KeyError as e:
            logging.debug('\t\t{}:\tnot set ({})'.format(propname.capitalize(), e))
            pass
